var musicPlayer = {
    context: document.getElementById("musicPlayer"),
    musicList: [], // 播放列表
    currentMusic: {
        id: 0,
        url: 'http://m8.music.126.net/20220217231735/b5f849a3858e3bcaea59d5d096c817fa/ymusic/9694/b4a1/86c6/43bd69ba48d7932dcf06359a0097b682.mp3',
        coverImgUrl: 'http://p3.music.126.net/d2YGirGfblLZv-3jCUI0RA==/18859922951355048.jpg',
        name: 'Isara',
        author: 'Eluveitie',
        duration: 0
    },
    autoplay: false,
    playState:false, // 播放状态 默认是停止状态
    playMode: 'listLoop'  // 默认列表循环 listLoop：列表循环 ，order：顺序播放，simple：单曲循环
}
// musicPlayer.context.onpause = function () {
//     console.log('onpause -- ')
//     // 判断音乐播放器是点了暂停还是停止播放
//     if (musicPlayer.context.ended) {
//         musicPlayer.playState = false;
//         //停止播放时，判断播放模式是啥
//         modePlay();
//     }
// };
/**
 * 判断播放模式
 */
function modePlay(mode){
    switch (mode) {
        case 'simple': // 单曲播放
            simplePlay();
            break;
        case 'listLoop': // 列表循环
            loopPlay();
            break;
        case 'order': // 顺序播放
            orderPlay();
            break;
        default:
            loopPlay();
            break;
    }
}
function simplePlay(){ // 单曲播放
    let index = musicPlayer.musicList.indexOf(musicPlayer.currentMusic);
    readyNext(index);
}

function loopPlay(){ // 列表循环
    let playingListLength = musicPlayer.musicList;
    let currentIndex =musicPlayer.musicList.indexOf(this.currentPlayingMusic)
    if (currentIndex === playingListLength - 1) {
        this.readyNext(0)
    } else {
        this.readyNext(currentIndex + 1)
    }
}
function orderPlay(){ // 顺序播放
    let playingListLength = musicPlayer.musicList.length;
    let currentIndex = musicPlayer.musicList.indexOf(this.currentPlayingMusic);
    if (currentIndex !== playingListLength - 1) {
        if (currentIndex < 0) {
            this.readyNext(0)
        } else {
            this.readyNext(currentIndex + 1);
        }
    }
}

function readyNext(index) { // 准备播放
    musicPlayer.currentMusic = musicPlayer.musicList[index];
    play();
}

function play(){
    musicPlayer.context.src = musicPlayer.currentMusic.url
    toggle();
}

/**
 * 播放或暂停
 */
function toggle() {
    if (!musicPlayer.musicList || musicPlayer.musicList.length === 0) {
        // musicPlayer.src = 'Eluveitie - Isara.mp3'
        var currentMusic =  eval("(" + localStorage.getItem("current_playing_music") + ")") ;
        if (currentMusic){
            musicPlayer.currentMusic = currentMusic.value ;
        }
        if (!musicPlayer.musicList){
            musicPlayer.musicList = []
        }
        musicPlayer.musicList.push(musicPlayer.currentMusic)
        musicPlayer.context.src = 'Eluveitie - Isara.mp3' ;//musicPlayer.currentMusic.url
    }
    if (musicPlayer.playState) {
        musicPlayer.context.pause();
    } else {
        musicPlayer.context.play();
    }
    musicPlayer.playState = !musicPlayer.playState

}
